<template>
  <div class="currency">
    <v-loading v-if="loading" />
    <!-- 操作买卖区 -->
    <div class="currency-top">
      <!-- 左区 -->
      <div class="currency-top-left">
        <div class="currency-top-left-buy">
          <div class="btn-group">
            <van-button :color="'#0BBA99'" @click="BuyOrCellClick('Buy')">{{ $t('Currency.buy') }}</van-button>
            <van-button :color="'#EE3E57'" @click="BuyOrCellClick('Sell')">{{ $t('Currency.sell') }}</van-button>
          </div>
          <van-dropdown-menu class="select">
            <van-dropdown-item v-model="buyStyle" :options="option" @change="buyStyleChange" />
          </van-dropdown-menu>
        </div>
      
        <van-divider />
        <template>
          <!-- 市限委托 -->
          <div class="currency-top-left-optimalPrice" @click.stop>
            <p v-if="buyStyle == 1">
              {{ $t('Currency.Trade at the current best price') }}
            </p>
            <van-field name="stepper" v-else>
              <template #input>
                <van-stepper v-model="buyPrice" @blur="handlePrice(buyPrice, 1)" min="0" />
              </template>
            </van-field>
          </div>
          <!-- 操作金额 -->
          <van-field class="transactionAmount" v-model="transactionAmount" center type="number" @input="handlePrice(transactionAmount, 2)" :placeholder="buy_or_sell === 'Buy' ? $t('Currency.transaction amount') : $t('Currency.quantity')">
            <template #button>
              <van-button size="small">{{ uunit }}</van-button>
            </template>
          </van-field>
          <!--可用金额 -->
          <div class="available">
            <span>{{ $t('Currency.Available') }}:</span>
            <span>
              <van-icon :name="isHiddenBalance" @click="showHiddenAmounts()" />
              {{ isHiddenBalance == 'eye' ? this.buy_or_sell === 'Buy' ? this.myTurnover : this.myNumber : '***' }} {{ uunit }}
              <van-icon name="replay" @click="getExchangeRate()" />
            </span>
          </div>
          <!-- 快捷金额 -->
          <div class="progress">
            <div v-for="(item, index) in progressList" :key="index" :class="switchClass(item)" @click="progressClick(item, index)">
              <div v-if="item !== 0">
                <p></p>
                <span>{{ item }}%</span>
              </div>
            </div>
          </div>
          <!-- 下单按钮 -->
          <div class="buy-dot">
            <van-button @click="popup_buy_sell_click" :color="buy_or_sell === 'Buy' ? '#0BBA99' : '#EE3E57'">{{ buy_or_sell === 'Buy' ? $t('Currency.buy') : $t('Currency.sell') }}</van-button>
          </div>
        </template>
      </div>
      <!-- 右区 -->
      <div class="currency-top-right">
        <div class="currency-top-right-title">
          <p :style="{ color: colorStyle() }">{{ $t('Currency.Current price') }}</p>
          <p :style="{ color: colorStyle() }">{{ tickerData.lastPrice }}</p>
        </div>
        <div class="currency-top-right-title">
          <p>{{ $t('Currency.price') }} ({{ currencyList && currencyList[1] }})</p>
          <p>{{ $t('Currency.quantity') }} ({{ currencyList && currencyList[0] }})</p>
        </div>
        <div class="currency-top-right-content">
          <div v-for="(item, index) in bibiPriceList" :key="index" style="position: relative">
            <!-- <div class="bg_class" :style="{ width: item.widthrate, background: item.direction === 'buy' ? 'rgba(139,195,74,0.2)' : 'rgba(220,38,38,0.2)' }" style="position: absolute; right: 0; height: 100%; background-color: rgba(220, 38, 38, 0.2)"></div> -->
            <p :style="{ color: item.direction === 'buy' ? '#0BBA99' : '#EE3E57' }">{{ item.price && item.price }}</p>
            <p>{{ item.amount && item.amount }}</p>
          </div>
        </div>
      </div>
    </div>
    <!-- 订单列表 -->
    <template>
      <div class="currency-driver"></div>
      <div class="currency-bottom">
        <van-cell class="bottom-title" :title="$t('Currency.entrust') + ' (' + currentOrderCount + ')'">
          <!-- 使用 right-icon 插槽来自定义右侧图标 -->
          <template #right-icon>
            <img @click="jumpRouter('/trade/ordernumber')" src="@/assets/img/ClipboardText@2x(1).png" alt="" />
          </template>
        </van-cell>
        <div class="bottom-content">
          <van-empty v-if="currentOrderList.length === 0" :description="$t('info.info7')" />
          <div class="list-data" v-else>
            <div class="data-every" v-for="(item, index) in currentOrderList" :key="index">
              <div class="every-title">
                <p class="title-left">
                  <span :style="{ color: item.direction == 1 ? '#0BBA99' : '#EE3E57' }">
                    {{ item.direction == 1 ? $t('Currency.buy') : $t('Currency.sell') }}
                  </span>
                  <span>{{ item.symbol }}</span>
                </p>
                <van-tag type="danger" size="medium" @click="revokeSpotOrder(item.id)">{{ $t('Currency.Click to cancel order') }}</van-tag>
              </div>
              <div class="every-content">
                <div class="data">
                  <div>
                    <p class="text_left">{{ $t('Currency.Order No') }}</p>
                    <p class="text_left">{{ item.order_no }}</p>
                  </div>
                  <div>
                    <p>{{ $t('Currency.Commission time') }}</p>
                    <p>{{ item.trust_time }}</p>
                  </div>
                  <div>
                    <p>{{ $t('Currency.End Time') }}</p>
                    <p>-</p>
                  </div>
                  <div>
                    <p class="text_left">{{ $t('Currency.Delegate type') }}</p>
                    <p class="text_left">{{ item.trust_type == 1 ? $t('Currency.market price') : $t('Currency.limit price') }}</p>
                  </div>
                  <div>
                    <p>{{ `${$t('Currency.Amount of commission')}(${item.symbol_pricing})` }}</p>
                    <p>{{ item.trust_amount }}</p>
                  </div>
                  <div>
                    <p>{{ $t('Currency.Order price') }}</p>
                    <p>{{ item.trust_price }}</p>
                  </div>
                  <div>
                    <p class="text_left">{{ $t('Currency.Transaction price') }}</p>
                    <p class="text_left">-</p>
                  </div>
                  <div>
                    <p>{{ `${$t('Currency.trading volume')}(${item.symbol_base})` }}</p>
                    <p>-</p>
                  </div>
                  <div>
                    <p>{{ `${$t('Currency.handling fee')}(${item.symbol_base})` }}</p>
                    <p>-</p>
                  </div>
                </div>
                <van-divider />
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
    <!-- 下单弹出层 -->
    <van-popup class="place-popup" v-model="buy_or_sell_popup">
      <div class="place-popup-title">
        <p>{{ $t('Currency.Order Confirmation') }}</p>
        <van-icon name="cross" @click="buy_or_sell_popup = false" />
      </div>
      <van-divider />
      <div class="place-popup-content">
        <div class="place-popup-content-info">
          <p>
            <span class="label">{{ $t('Currency.name') }}</span>
            <span class="value">{{ symbol }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Currency.direction') }}</span>
            <span
              class="value"
              :style="{
                color: buy_or_sell === 'Buy' ? '#0BBA99' : '#EE3E57'
              }"
            >
              {{ buy_or_sell === 'Buy' ? $t('Currency.buy') : $t('Currency.sell') }}
            </span>
          </p>
          <p>
            <span class="label">{{ $t('Currency.Way') }}</span>
            <span class="value">{{ buyStyle === 1 ? $t('Currency.Market mandate') : $t('Currency.limit order') }}</span>
          </p>
          <p v-if="buyStyle === 2">
            <span class="label">{{ $t('Currency.Order price') }}</span>
            <span class="value">{{ buyPrice }}</span>
          </p>
          <p>
            <span class="label">{{ $t('Currency.transaction amount') }}</span>
            <span class="value">{{ transactionAmount }}</span>
          </p>
        </div>
      </div>
      <div class="place-popup-footer">
        <van-button :color="'#DAAB51'" round @click="confirmOrder">{{ $t('Currency.Confirm order') }}</van-button>
      </div>
    </van-popup>
  </div>
</template>

<script>
export default {
  name: 'currency',
  props: {
    isDayTime: {
      type: Boolean,
      default: false
    },
    symbol: {
      type: String,
      default: ''
    }
  },
  computed: {
    socketMsgs() {
      return this.$websocket.getters.socketMsgs
    },
    addClass() {
      return this.buy_or_sell === 'Sell' ? 'progress-buy-active' : 'progress-sell-active'
    }
  },
  watch: {
    socketMsgs: function (data) {
      if (data.type == 'market') {
        this.tickerData = data.data
      } else if (data.type == 'trade') {
        if (data.data != undefined && data.data.length != 0) {
          let array1 = this.bibiPriceList
          let array2 = data.data
          let array3 = array2.concat(array1).slice(0, 12)
          this.bibiPriceList = array3
        }
      } else if (data.type == 'deal') {
        if (data.data.data.length > 0) {
          this.currentOrderList = data.data.data
          this.currentOrderCount = data.data.data.length
        } else {
          this.currentOrderList = []
          this.currentOrderCount = 0
          this.closeDeal()
        }
      }
    }
  },
  data() {
    return {
      expiryTimeList:[],
      textColor: this.isDayTime ? '#1A1A1A' : '#DDE2EC',
      buy_or_sell: 'Buy', //购买类型
      buyStyle: 1, //市价限价
      option: [
        // 类型列表
        { text: this.$t('Currency.Market mandate'), value: 1 },
        { text: this.$t('Currency.limit order'), value: 2 }
      ],
      buyPrice: '0', //限价价格
      transactionAmount: null, //交易金额
      progressList: [0, 20, 50, 75, 100], //快捷金额
      progressValue: 0, //进度条值
      uunit: '', //计价货币
      bibiPriceList: [], //买一卖一列表
      buy_or_sell_popup: false, //是否弹出下单框
      currentOrderList: [], //委托订单列表
      currentOrderCount: 0, //委托订单数量
      loading: false, //是否加载
      currencyList: [], // 兑币列表
      myTurnover: '', // 交易额余额
      myNumber: '', // 数量余额
      tickerData: {}, // 货币数据
      isHiddenBalance: "closed-eye" //隐藏图标
    }
  },
  activated() {
    this.geUunit(this.symbol)
    this.getConfig()
    this.getBboData()
    this.getDealData()
    this.getExchangeRate()
  },
  created() {
    this.geUunit(this.symbol)
    this.getConfig()
    this.getBboData()
    this.getDealData()
    this.getExchangeRate()
  },
  deactivated() {
    this.closeBboData()
    this.closeDeal()
  },
  destroyed() {
    this.closeBboData()
    this.closeDeal()
  },
  methods: {
    // 初始化
    init(symbol) {
      this.geUunit(symbol)
      this.getBboData()
      this.getDealData()
      this.getExchangeRate()
      this.buyStyle = 1
    },
    // 涨跌颜色
    colorStyle() {
      return this.tickerData.lastPrice >= this.tickerData.open ? '#1cad90' : '#EE3E57'
    },
    // 订阅逐笔行情
    getBboData() {
      var timer = setInterval(() => {
        if (this.$websocket.getters.getState) {
          this.$websocket.dispatch('webSocketSend', { type: 'trade', symbol: this.symbol })
          clearInterval(timer)
        }
      }, 1)
    },
    // 取消订阅逐笔行情
    closeBboData() {
      this.$websocket.dispatch('webSocketSend', { type: 'stop', method: 'trade' })
    },
    // 订阅委托中订单
    getDealData() {
      var userInfo = localStorage.getItem('userInfo')
      if (userInfo == null) return
      var userInfoToken = JSON.parse(userInfo).token
      
      var timer = setInterval(() => {
        if (this.$websocket.getters.getState) {
          this.$websocket.dispatch('webSocketSend', { type: 'deal', symbol: this.symbol, token: userInfoToken })
          clearInterval(timer)
        }
      }, 1)
    },
    // 取消订阅委托中订单
    closeDeal() {
      this.$websocket.dispatch('webSocketSend', { type: 'stop', method: 'deal' })
    },
    // 切换买卖
    BuyOrCellClick(val) {
      this.buy_or_sell = val
      this.progressValue = 0
      this.transactionAmount = null
      this.geUunit(this.symbol)
      this.buyStyleChange(this.buyStyle)
      this.getExchangeRate()
    },
    // 获取计价货币
    geUunit(symbol) {
      this.currencyList = symbol.split('/')
      if (this.buy_or_sell === 'Buy') {
        this.uunit = this.currencyList[1]
      } else {
        this.uunit = this.currencyList[0]
      }
    },
    // 获取币种余额
    async getExchangeRate() {
      var userInfo = localStorage.getItem('userInfo')
      if (userInfo == null) {
        this.myTurnover = 0
        this.myNumber = 0
        return
      }

      this.loading = true
      await this.$https.get('/wallet/currencyBalance?type=0&currency=' + this.uunit).then(res => {
        if (res != undefined && res.code == 1) {
          if (this.buy_or_sell == 'Buy') {
            this.myTurnover = res.data
          } else {
            this.myNumber = res.data
          }
        }
      })
      this.loading = false
    },
    // 限价价格
    buyStyleChange(val) {
      val === 2 && (this.buyPrice = this.tickerData.lastPrice)
    },
    // 获取当前委托
    getCurrentMandate() {
      return this.$https.post('/market/getCurrentMandate', { symbol: this.symbol }).then(res => {
        if (res.code === 0) {
          this.currentOrderList = res.data.data.map(item => {
            let list = item.symbol.split('/')
            item.delegatedCurrency = list[0] ? list[0] : ''
            item.delegatedCurrency1 = list[1] ? list[1] : ''
            return item
          })
          this.currentOrderCount = res.data.count
        }
      })
    },
    // 进度条
    switchClass(item) {
      if (this.buy_or_sell === 'Buy') {
        return { 'progress-buy-active': this.progressValue >= item }
      } else {
        return { 'progress-sell-active': this.progressValue >= item }
      }
    },
    // 点击快捷下注金额
    progressClick(item) {
      if (this.progressValue === item) {
        this.progressValue = 0
      } else {
        this.progressValue = item
      }
      let money = this.buy_or_sell === 'Buy' ? this.myTurnover : this.myNumber
      this.transactionAmount = ((money * this.progressValue) / 100).toFixed(8)
    },
    // 弹出下单框
    popup_buy_sell_click() {
      var userInfo = localStorage.getItem('userInfo')
      if (userInfo == null) {
        this.$dialog
          .confirm({
            title: this.$t('info.info20'),
            confirmButtonText: this.$t('info.info21'),
            cancelButtonText: this.$t('info.info11'),
            confirmButtonColor: 'rgb(218, 171, 81)',
            cancelButtonColor: 'rgb(218, 171, 81)',
            theme: 'round-button'
          })
          .then(() => {
            this.$router.push('/signIn')
          })
          .catch(() => {})
        return
      }

      if (this.transactionAmount > 0) {
        this.buy_or_sell_popup = true
      } else {
        let info = this.buy_or_sell === 'Buy' ? 'Please input transaction amount' : 'Please enter quantity'
        this.$toast(this.$t(`Currency.${info}`))
      }
    },
    // 跳转路由
    jumpRouter(router) {
      this.$router.push(router)
    },
    // 确认下单
    async confirmOrder() {
      let params = {
        symbol: this.symbol,
        direction: this.buy_or_sell === 'Buy' ? 1 : 2,
        type: this.buyStyle,
        amount: this.transactionAmount,
        price: this.buyStyle === 1 ? '0' : this.buyPrice
      }
      this.loading = true
      await this.$https.post('/coin/addSpotOrder', params).then(res => {
        if (res != undefined && res.code == 1) {
          this.getExchangeRate()
          this.progressValue = 0
          this.transactionAmount = null
          if (this.currentOrderCount == 0 && this.buyStyle == 2) {
            this.getDealData()
          }
        }
      })
      this.loading = false
      this.buy_or_sell_popup = false
    },
    // 撤销委托订单
    revokeSpotOrder(id) {
      this.$dialog
        .confirm({
          title: this.$t('info.info17'),
          confirmButtonText: this.$t('info.info10'),
          cancelButtonText: this.$t('info.info11'),
          confirmButtonColor: 'rgb(218, 171, 81)',
          cancelButtonColor: 'rgb(218, 171, 81)',
          theme: 'round-button'
        })
        .then(() => {
          this.$https.post('/coin/revokeSpotOrder', { id: id }).then(res => {})
        })
        .catch(() => {})
    },
    // 限制保留八位小数
    handlePrice(val, type) {
      val += ''
      if (val !== '' && val.substr(0, 1) === '.') {
        val = ''
      }
      val = val.replace(/^0*(0\.|[1-9])/, '$1') //解决 粘贴不生效
      val = val.replace(/[^\d.]/g, '') //清除“数字”和“.”以外的字符
      val = val.replace(/\.{2,}/g, '.') //只保留第一个. 清除多余的
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      val = val.replace(/^(\-)*(\d+)\.(\d\d\d\d\d\d\d\d).*$/, '$1$2.$3') //只能输入八个小数
      if (val.indexOf('.') < 0 && val !== '') {
        if (val.substr(0, 1) === '0' && val.length === 2) {
          val = val.substr(1, val.length)
        }
      }
      if (type == 1) {
        this.buyPrice = val
      } else if (type == 2) {
        this.transactionAmount = val
      }
    },
    showHiddenAmounts(){
      if(this.isHiddenBalance == 'closed-eye'){
        this.isHiddenBalance = 'eye';
      } else {
        this.isHiddenBalance = 'closed-eye';
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import url('./index.less');
</style>
